package main.java.com.async.tools;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.PrintStream;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;



import org.apache.logging.log4j.LogManager;

public class LogMessage {

	private static final String ROOT_PATH = System.getProperty("user.dir");

	private static final String TEMP_LOG_FILE = "log4j_use_error.txt";

	private static Logger logger = null;

	static {

		try {
			loadConfigForLog4j2();
		}
		catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		logger = LogManager.getLogger(LogMessage.class);
	}


	/**
	 * 异常信息处理和显示
	 *
	 * @param e 异常
	 * @throws FileNotFoundException
	 */
	public static void logError(Exception e) throws FileNotFoundException {
		try {
			logger.error("程序异常原因：", e);
		}
		catch (Exception e1) {
			// TODO: handle exception
			e1.printStackTrace(new PrintStream(TEMP_LOG_FILE));
		}
	}

	/**
	 * 异常信息处理和显示
	 * @param e 异常
	 * @param explainInfo 对已知异常的解释信息
	 * @throws FileNotFoundException
	 */
	public static void logError(Exception e, String explainInfo) throws FileNotFoundException {
		try {
			logger.error("程序异常错误：" + explainInfo, e);
		}
		catch (Exception e1) {
			// TODO: handle exception
			e1.printStackTrace(new PrintStream(TEMP_LOG_FILE));
		}
	}

	/**
	 * 异常信息处理和显示
	 *
	 * @param e 异常
	 * @throws FileNotFoundException
	 */
	public static void logWarn(Exception e) throws FileNotFoundException {
		try {
			logger.warn("程序异常警告：", e);
		}
		catch (Exception e1) {
			// TODO: handle exception
			e1.printStackTrace(new PrintStream(TEMP_LOG_FILE));
		}
	}

	private static void loadConfigForLog4j2() throws FileNotFoundException {
		String log4j2ConfigPath = ROOT_PATH + "//log//config//log4j2.xml";
		File logConfigFile = new File(log4j2ConfigPath);
		if (!logConfigFile.exists()) {
			System.out.println("日志配置文件不存在,请到./log/config路径下检查文件是否存在");;
			return;
		}

		try {
//			加载log配置并初始化
			ConfigurationSource source = new ConfigurationSource(new FileInputStream(logConfigFile));
			Configurator.initialize(null, source);
		}
		catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace(new PrintStream(TEMP_LOG_FILE));
		}
	}
}
